<?php
namespace Admin\Controller;

use Think\Controller;

class TracingController extends RightController
{
    // 加载初始化内容页,并检索
    public function index()
    {
        //判断分页时搜索条件
        if (I("get.p")) {
            $where = session("QG_SEARCH_WHERE_tracing");
            $this->assign("params", session("QG_SEARCH_PARAMS_tracing"));
            $where = empty($where) ? "1" : $where;
            $pageSize = session("QG_SEARCH_SIZE_tracing");
        } else {
            //清除session存储
            session("QG_SEARCH_WHERE_tracing", null);
            session("QG_SEARCH_PARAMS_tracing", null);
            session("QG_SEARCH_SIZE_tracing", null);
            $pageSize = I("post.pageSize");

            $where = "1";
        }

        // POST数据提交，重新组合检索条件
        if (IS_POST) {
            unset($_GET["p"]);
            $where = $this->searchCondition();
        }
		
		// 分页输入
        if(empty($pageSize)){
            $pageSize = 10;
        }

        // 总条数
        $count = M('tracing')
            ->alias("t")
            ->where($where)
            ->count();
        $page = new \Admin\Model\Page($count, $pageSize);
        $show = $page->show();

        // 进行分页数据查询
        $list = M('tracing')
            ->alias("t")
            ->field("t.*")
            ->where($where)
            ->order('t.id DESC')
            ->limit($page->firstRow . ',' . $page->listRows)->select();
			
		// 统计
        $sum = M('tracing')
            ->alias("t")
            ->field("count(1) as countNum")
            ->where($where)
            ->order('t.id DESC')
            ->find();

        // 渲染查询条件到session
        session("QG_SEARCH_WHERE_tracing", $where);
		session("QG_SEARCH_PARAMS_tracing", I("post."));
		session("QG_SEARCH_SIZE_tracing", $pageSize);
		
		// 输出数据
        $this->assign("params", I("post."));
        $this->assign('list', $list);
        $this->assign('sum', $sum);
		$this->assign('lists', array(
            "page" => getDropdownList("pageSize" ,"" ,false),
            "tracingStatus" => getDropdownList("tracingStatus")
        ));
        $this->assign('page', $show);
        $this->display();
    }

    // 搜索条件
    public function searchCondition()
    {
        $where = "1";

        // 溯源号
        if (I('post.sn')) {
            // 精确
            if (I('post.snCondition') == 1) {
                $where .= " AND t.sn='" . I("post.sn") . "'";
            } else {
                $where .= " AND t.sn LIKE '%" . I("post.sn") . "%'";
            }
        }

        // 状态
        if (I('post.status')) {
            $where .= " AND t.status='" . I("post.status") . "'";
        }

        // 创建时间
        if (I('post.createtimeStart') || I('post.createtimeEnd')) {
            // 起始日期
            if(I('post.createtimeStart')){
                $where .= " AND t.createTime>='" . I("post.createtimeStart") . "'";
            }
            // 结束日期
            if(I('post.createtimeEnd')){
                $where .= " AND t.createTime<='" . I("post.createtimeEnd") . " 23:59:59'";
            }
        }

        // 更新时间
        if (I('post.updatetimeStart') || I('post.updatetimeEnd')) {
            // 起始日期
            if(I('post.updatetimeStart')){
                $where .= " AND t.updateTime>='" . I("post.updatetimeStart") . "'";
            }
            // 结束日期
            if(I('post.updatetimeEnd')){
                $where .= " AND t.updateTime<='" . I("post.updatetimeEnd") . " 23:59:59'";
            }
        }

        return $where;
    }

    // 生成
    public function add()
    {
        if (IS_POST) {
            // 数据
            $num = I('post.num');

            if(empty($num)){
                $this->ajaxError("数量错误！");
            }

            for ($i = 0; $i < $num; $i++) {
                // 溯源号
                $data['sn'] = $this->getUniqueCode();
                $data['status'] = 1;
                $data['createTime'] = now();
                $data['updateTime'] = now();
                $datas[] = $data;
                $csvDatas[] = array($data['sn']);
            }

            //创建数据
            $result = M('tracing')->addAll($datas);

            if ($result) {
                // 下载文件
                downloadHeaders("export_" . date("Y-m-d") . ".csv");
                echo array2csv($csvDatas);
                unset($csvDatas);
                die();
            } else {
				$this->error("生成失败！");
            }
        } else {
            $this->display();
        }
    }

    // 选中重新下载
    public function download(){
        // 获取设置无效的id
        $ids = I("post.ids");

        $result = M('tracing')->where(array("id" => array("IN" ,$ids)))->select();

        for ($i = 0; $i < count($result); $i++) {
            $csvDatas[] = array($result[$i]['sn']);
        }
        // 下载文件
        downloadHeaders("export_" . date("Y-m-d") . ".csv");
        echo array2csv($csvDatas);
        unset($csvDatas);
        die();
    }

    // 批量设置为失效
    public function invalid(){
        // 获取设置无效的id
        $ids = I("post.ids");

        $result = M('tracing')->where(array("id" => array("IN" ,$ids)))->setField("status" , "3");

        if ($result !== false) {
            $this->ajaxSuccess("更新成功！");
        } else {
            $this->ajaxError("更新失败！");
        }
    }

    // 流转记录
    public function flow(){
        $id = I("id");
        // 订单详情
        $list = M('flow')
            ->alias("t")
            ->join(" LEFT JOIN agen ba ON ba.id = t.beforeId")
            ->join(" LEFT JOIN agen aa ON aa.id = t.afterId")
            ->field("t.id,ba.phone as beforeAccount,ba.name as beforeName,aa.phone as afterAccount,aa.name as afterName,t.createTime,t.info")
            ->where(array("t.sourceType" => 3, "t.sourceId" => $id))
            ->select();

        $this->assign("list" ,$list);
        $this->display();
    }
}